import Schema from 'validate'
// 创建手机号规则
const mobileSchema = new Schema({
  mobile: {
    type: String,
    required: true,
    match: /^1[3-9]\d{9}$/,
    message: '请输入正确的手机号'
  }
})
const codeSchema = new Schema({
  code: {
    type: String,
    required: true,
    match: /^\d{6}$/,
    message: '验证码格式不正确'
  }
})

Page({
  data: {
    countDownVisible: false,
    // 手机
    mobile: '',
    // 倒计时时间
    timeData: {},
    // 验证码
    code: ''
  },
  // 点击发送验证码
  async goCode () {
    const mobile = {
      mobile: this.data.mobile
    }
    // 校验手机号
    const errors = mobileSchema.validate(mobile)
    // 如果校验有错，弹提示，和阻止后面请求的发送
    // console.log(errors)
    if (errors.length) {
      console.log(errors)
      wx.utils.toast(errors[0].message)
      return
    }
    const res = await wx.http({
      url: '/code',
      data: mobile
    })
    console.log(res)
    this.setData({
      countDownVisible: true
    })
  },
  // 验证码到点刷新
  countDownChange (ev) {
    this.setData({
      timeData: ev.detail,
      countDownVisible: ev.detail.minutes === 1 || ev.detail.seconds > 0
    })
  },
  // 登录
  async submitForm () {
    const { mobile, code } = this.data
    // 校验手机号
    const errorsMobile = mobileSchema.validate({
      mobile
    })
    if (errorsMobile.length) {
      wx.utils.toast(errorsMobile[0].message)
      return
    }
    // 校验验证码
    const errorsCode = codeSchema.validate({
      code
    })
    if (errorsCode.length) {
      wx.utils.toast(errorsCode[0].message)
      return
    }
    // 登录获取数据
    const res = await wx.http({
      url: '/login',
      method: 'post',
      data: {
        mobile,
        code
      }
    })
    console.log(res)
    wx.utils.toast('登录成功')
    const { token, refreshToken } = res.data
    const app = getApp()
    // 将获取到的toke存储在app里
    app.setToken(token, refreshToken)
    // console.log(app.token)
    // console.log(this.redirect)
    if (this.redirect) {
      wx.reLaunch({
        url: '/' + this.redirect
      })
      // console.log(111)
    } else {
      wx.switchTab({
        url: '/pages/index/index'
      })
      // console.log(123)
    }
  },
  onLoad ({ redirect }) {
    console.log(redirect)
    this.redirect = redirect
  }
})
